﻿using System.Text.Json;
using System.Text.Json.Nodes;
using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using ExchangeClient.SAP.Model;
using ExchangeClient.Yidea;
using HKH.Configuration;
using HKH.Mef2.Integration;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.Crypt.Dsig;
using OfficeOpenXml;
using SyncService.Abstractions.Services;
using SyncService.Results;
using SyncService.WebHost.Controllers;


namespace SyncService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TestController : MefControllerBase
    {
        private UserDefines _setting;
        private ExtendFields _extendFields;
        private readonly ILogger<EsbController> _logger;
        public TestController(CompositionContainer mefContainer, UserDefines setting, ExtendFields extendField, ILogger<EsbController> logger) : base(mefContainer)
        {
            _setting = setting;
            _extendFields = extendField;
            _logger = logger;
        }
        [HttpGet]
        [Route("ServiceTest")]
        public void ServiceTest(string serviceName = "UpdateStaffGroup")
        {
            var services = MefContainer.GetExports<Lazy<ISyncService, Dictionary<string, object>>>();

            var syncService = services.First(x => x.Metadata![ExchangeClient.Abstractions.YdConstants.ID].ToString() == serviceName).Value;
            syncService.Execute(null);

        }
        [HttpGet]
        [Route("ReadJson2")]
        public void ReadJson()
        {
            var masterAsset = new List<Asset>();
            var jsonFile = Path.Combine(SyncService.Common.Constants.WebRootPath, "");
            var mdJson = System.IO.File.ReadAllText(jsonFile);
            masterAsset = JsonSerializer.Deserialize<List<Asset>>(mdJson);

        }
        [HttpPost]
        [Route("ReadExcel")]
        public void ReadExcel()
        {
            SyncService.Common.Excel.ReadExcel.ReadNetWorkFile("https://ydassetpicture.oss-cn-beijing.aliyuncs.com/MediaResources/176908/ExtensionField/20240509/abbe523178fa4ba59148da06abe74053.xlsx");
        }
        [HttpGet]
        [Route("YideaTest")]
        public string YideaTest()
        {
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![ExchangeClient.Abstractions.YdConstants.ID].ToString() == ExchangeClient.Abstractions.YdConstants.YIDEA).Value as YideaClient;
            QueryParam queryParam = new QueryParam();
            queryParam.FilterObject = new JsonObject
            {
                ["assetTypeCodeIn"] = "Z101,Z01I,Z01A,GC01,GC02,GC03,GC04,GC05,GC06,GC07,GC08,GC09,GC10,GC11,GC12,GC14,GC15,GC16,GC17,GC18,GC99,GC19,GC20,GC21,GC22,GC23,GC24,GC25,GC26,GC27,GC28,GC29,GC92,Z102,Z02I,Z02A,GF01,GF02,GF03,GF04,GF05,GF99,Z103,Z03I,GE01,GE02,GE06,GE07,GE11,GE12,GE13,GE14,GE15,GE16,GE17,GE19,GE20,GE22,GE23,GE26,GE28,GE29,GE30,GE32,GE46,GE47,GE48,GE63,GE71,GE72,GE77,GE78,GE97,GE98,GE100,GE101,GE102,GE104,Z03A,GE03,GE04,GE05,GE08,GE09,GE10,GE18,GE21,GE24,GE25,GE27,GE31,GE33,GE34,GE35,GE36,GE37,GE38,GE39,GE40,GE41,GE42,GE43,GE44,GE45,GE49,GE50,GE51,GE52,GE53,GE54,GE55,GE56,GE57,GE58,GE59,GE60,GE61,GE62,GE64,GE65,GE66,GE67,GE68,GE69,GE70,GE73,GE74,GE75,GE76,GE99,GE79,GE80,GE81,GE83,GE86,GE87,GE88,GE89,GE90,GE91,GE92,GE93,GE94,GE95,GE96,GE105,GE106,GE107,GE108,GE109,Z104,Z04I,Z04A,GA01,GA02,GA03,GA99,Z105,Z05I,Z05A,GG01,GG02,GG03,GG99,Z106,Z06I,Z06A,GB01,GB02,GB03,GB04,GB05,GB99,Z107,Z07I,Z07A,GH01,GH02,GH99,Z190,Z90I,Z90A,GI99,Z205,W05I,WA01,Z301,T01T,TA02,T01A,TA01,Z302,T02T,TB02,T02A,TB01,Z303,T03T,TC01,T03A,TC02,Z304,T04T,TD03,T04A,TD01,Z305,T05T,TD02,T05A,TD04,Z306,T06T,TE01,T06A,TE02,Z307,T07T,TF01,T07A,TF02,Z308,T08T,TJ01,T08A,TJ02,Z309,T09T,TK01,T09A,TK02,Z310,T10T,TG99,T10A,TG98,Z311,T11T,TH01,T11A,TH02,Z390,T90T,TG01,T90A,TG02,GE103,GE110,GE111,GE82,W05A,Z312,T12A,T12T,TD05,TD06,Z202,W02I,W02A,WA03"
            };
            queryParam.Take = 10000;
            List<Asset> assets = yideaClient.GetAssets(queryParam).ToList();

            using (FileStream fs = new FileStream("D:\\1.txt", FileMode.OpenOrCreate, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.BaseStream.Seek(0, SeekOrigin.End);
                foreach (var aseset in assets)
                {
                    var dataJson = JsonNode.Parse(aseset.DataJson).AsObject();
                    var time = dataJson["date_1700468589855"]?.ToString();
                    sw.WriteLine(aseset.Barcode + ":" + time);
                }

                sw.Flush();
                sw.Close();
                fs.Close();
            }
            #region MyRegion


            //using (FileStream fs = new FileStream("D:\\1.txt", FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    StreamWriter sw = new StreamWriter(fs);
            //    sw.BaseStream.Seek(0, SeekOrigin.End);
            //   for(int i=0;i<2;i++)
            //    {
            //        sw.WriteLine("用 Environment.NewLine 实现文本文件换行；");
            //    }

            //    sw.Flush();
            //    sw.Close();
            //    fs.Close();
            //}
            //var exField1 = new ExtendField
            //{
            //    FieldId = "select_1688707287868",
            //    FieldType = ExtendFieldType.Select,
            //    Name = "库存状态",
            //    Values = new ExtendFieldValues {
            //        new ExtendFieldValue { Value = "正常", ValueDefination = "{\"value\":\"正常\",\"label\":\"正常\",\"color\":{\"backgroundColor\":\"#45cb7f\",\"foreColor\":\"#ffffff\"}}" } ,
            //        new ExtendFieldValue { Value = "低于安全库存", ValueDefination = "{\"value\":\"低于安全库存\",\"label\":\"低于安全库存\",\"color\":{\"backgroundColor\":\"#f76368\",\"foreColor\":\"#ffffff\"}}" }
            //    }
            //};
            //var exField2 = new ExtendField
            //{
            //    FieldId = "assetTypeSelect_1688707324436",
            //    FieldType = ExtendFieldType.Select,
            //    Name = "资产分类"
            //};
            //var exField3 = new ExtendField { FieldId = "input_1688707345537", Name = "规格型号" };

            //var exFiledFilters = new ExtendFieldFilters() {
            //    new ExtendFieldFilter{ Field=exField2, Value="01001"},
            //    new ExtendFieldFilter{ Field=exField3, Value="规格1234"}
            //};
            //var userForm = new UserDefinedForm() { FormId = Guid.Parse("26c1c154-a3b9-40e7-bbe2-edf3ac6f61dd") };
            //var jsonData = new JsonObject
            //{
            //    { exField1.FieldId, exField1.CreateValueObject("正常") },
            //    { exField2.FieldId, exField2.CreateValueObject("01001","Switch") },
            //    { exField3.FieldId, exField3.CreateValueObject("FormTest") }
            //};

            //userForm.JsonData = JsonSerializer.Serialize(jsonData);
            //userForm.Id = Guid.Parse("16c4f94d-2103-413a-8625-5c4071a477a9");
            ////var r = yideaClient.UpdateUserDefinedForm(userForm, userForm);

            ////var json = yideaClient.GetUserDefinedForms(Guid.Parse("26c1c154-a3b9-40e7-bbe2-edf3ac6f61dd"), null).ToList();
            ////var json = yideaClient.GetUserDefinedForms(Guid.Parse("26c1c154-a3b9-40e7-bbe2-edf3ac6f61dd"), new QueryParam { FilterString = exFiledFilters.ToJson() }).ToList();

            ////var d=  yideaClient.GetDictionaryDetails(Guid.Parse("8c13d1bc-ce27-4c54-8bd3-78e2917c1027"), null).ToList();

            ////var dis = yideaClient.GetDistricts(new QueryParam { FilterString = "orderby=code&requireHierarchies=true&checkDistrictId=252641&yideaSubType=SysUser" }).ToList();
            ////orderby=code&take=50&skip=0&include=total&requireHierarchies=true&checkDistrictId=252641&yideaSubType=SysUser

            ////var j = new JsonObject();
            ////j.Add("districtCodeIn", new JsonArray { "A00101", "A00103", "A00104" });
            ////j.Add("deleted", 0);

            ////var assts = yideaClient.GetAssets(new QueryParam
            ////{
            ////    FilterObject = j
            ////}).ToList();

            ////var astTypes = yideaClient.GetAssetTypes(null).ToList();

            //var columns = new Dictionary<string, string>
            //{
            //    { "state", "状态" },
            //    { "barcode", "资产编码" },
            //    { "name", "资产名称" },
            //    { "masterAsset", "主资产编码" },
            //    { "assetTypeHierarchy", "资产类别" },
            //    { "subsidiaryStatus", "主附状态" },
            //    { "specs", "规格型号" },
            //    { "sn", "设备序列号" },
            //    { "amount", "金额" },
            //    { "useDepartmentHierarchy", "使用部门" },
            //    { "user", "使用人" },
            //    { "districtName", "区域名称(短)" },
            //    { "address", "存放地点" },
            //    { "supervisor", "管理人" },
            //    { "purchasedDate", "购入日期" },
            //    { "vendor", "供应商" },
            //    //{ "报废状态", "报废状态" },
            //    //{ "PO", "PO" },
            //    //{ "PO Date", "PO Date" },
            //    //{ "SNOW TAG", "SNOW TAG" },
            //    //{ "Host Name", "Host Name" }
            //};

            //var assetFileter = new
            //{
            //    //columnsSetting = JsonSerializer.Serialize( new Dictionary<string, string>() {
            //    //    {"signatureStatus","0:待签字,1:已签字,2:已驳回,4:审批中,5:已审批,6:已驳回,10:待签字,11:已签字,21:已驳回" },
            //    //    {"createdDate","yyyy-MM-dd HH:mm"}
            //    //    })
            //    //,
            //    downloadFile = true,
            //    //RequireHierarchies = true,
            //    //FilterByPermission = true,
            //    //filterInExtensions = true,
            //    //deleted = 0,
            //    //orderby = "-id",
            //    //_uiculture = "zh",
            //    columns = JsonSerializer.Serialize(columns),
            //    barcode = "SHDR20230700000030"//,
            //                                  // extensionFilters = new string[] { }
            //};
            //// var ass=yideaClient.GetAssets(new QueryParam { FilterObject = new JsonObject { { "barcode", "SHDR20230700000022" }, { "requireHierarchies", true }, { "filterByPermission", true } } }).ToList();

            //var fileUrl = yideaClient.GetExportFile("/private/Asset/Export/readonly?yideaSubType=SysUser", assetFileter);
            #endregion
            return "";
        }
        /// <summary>
        /// 过期无报文处理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ExpiryDisposal")]
        public IActionResult ExpiryDisposal()
        {
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            RequestBase<SAPAssetClear> addAssetClearRequeste = new RequestBase<SAPAssetClear>();
            BaseInfo baseInfo = new BaseInfo();
            baseInfo.interID = "fico323";
            baseInfo.msgID = "005056A71F3E1EEE83E33DBE685AE065";
            baseInfo.transID = Guid.NewGuid();
            baseInfo.sender = "LAM";
            baseInfo.receiver = "SAP";
            baseInfo.sendTime = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
            addAssetClearRequeste.baseInfo = baseInfo;
            List<SAPAssetClear> busiInfo = new List<SAPAssetClear>();
            int flag = 1;


            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = "CLN202502120005"
            });


            var VformId = _setting.First(x => x.Name == "报废自定义表单");
            var clearquery = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();


            var datajson = clearquery.Data["dataJson"].ToString();
            JObject jObj = JObject.Parse(datajson);
            // 获取 table_1690336801324 对应的 JArray
            JArray jArray = jObj["table_1690336801324"] as JArray;

            foreach (var item in jArray)
            {
                SAPAssetClear assetClear = new SAPAssetClear();
                assetClear.ZDJBH = clearquery.Data["serialNo"].ToString();
                assetClear.ZDJLX = "ZCBF";
                assetClear.ZDJBH_IT = flag.ToString();//行项目
                assetClear.BUKRS = item["input_1691661510671"]?.ToString();//公司代码
                assetClear.ANLN1 = item["input_1691544111906"]?.ToString();//sap资产编码  财务编码
                assetClear.BUDAT = DateTime.Now.ToString("yyyyMMdd");//过账日期
                assetClear.SGTXT = assetClear.ANLN1 + "资产报废"; // 备注
                assetClear.ZBFLX = "BF01";//报废  类型编码 
                assetClear.ZBFLXTXT = "固定资产报废";//报废类型描述
                busiInfo.Add(assetClear);

                flag++;
            }

            addAssetClearRequeste.busiInfo = busiInfo;
            string jsonString = JsonSerializer.Serialize(addAssetClearRequeste);

            return Ok(new ApiResult(0, "", jsonString));
        }
        /// <summary>
        /// 根据调拨单号生成退库和领用单据
        /// </summary>
        /// <param name="SerialNo"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LifeTKandLY")]
        public IActionResult LifeTKandLY()
        {


            List<string> SerialNoList = new List<string>();
            string filePath = @"E:\YDYD\需要处理的单据.xlsx";
            // 【关键】设置许可证上下文，放在所有 EPPlus 操作之前
            // 【关键】设置许可证
            string resultstring = string.Empty;
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                // 获取第一个工作表（可根据实际Sheet名称修改，如 package.Workbook.Worksheets["Sheet1"]）
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                // 获取最大行号（已使用的行）
                int maxRow = worksheet.Dimension.End.Row;

                // 遍历 A 列（编号所在列，可根据实际列调整，如 worksheet.Cells[row, 2] 代表 B 列）
                for (int row = 1; row <= maxRow; row++)
                {
                    // 读取单元格值并转换为字符串
                    string cellValue = worksheet.Cells[row, 1].Value?.ToString();
                    if (!string.IsNullOrEmpty(cellValue))
                    {
                        SerialNoList.Add(cellValue);
                        _logger.LogInformation($"\n调拨单：{cellValue}，已加入队列");

                    }
                    else
                    {
                        _logger.LogInformation($"\n第{row}行为空");
                    }
                }
            }
            SerialNoList = SerialNoList.Distinct().ToList();
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            foreach (var item in SerialNoList)
            {
                var condition = new JsonArray();
                condition.Add(new JsonObject()
                {
                    ["field"] = "serialNo",
                    ["type"] = "input",
                    ["label"] = "流水号",
                    ["opt"] = "Equal",
                    ["val"] = item
                });
                CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

                var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
                var assetList = datajson["table_1690536110546"].AsArray();
                var TuiKu = GenerateRefund(assetList, order, "公司内调拨");
                var LingYong = GenerateReceive(assetList, order, "公司内调拨");

                if (TuiKu)
                {
                    resultstring += $"\n调拨单号：{item}，生成退库成功";
                    _logger.LogInformation("调拨单号：{item}，生成退库成功");
                }
                else
                {
                    resultstring += $"\n调拨单号：{item}，生成退库失败";
                    _logger.LogInformation($"调拨单号：{item}，生成退库失败");
                }
                if (LingYong)
                {
                    resultstring += $"调拨单号：{item}，生成领用成功";
                    _logger.LogInformation($"调拨单号：{item}，生成领用成功");
                }
                else
                {
                    resultstring += $"\n调拨单号：{item}，生成领用失败";
                    _logger.LogInformation($"调拨单号：{item}，生成领用失败");
                }

                condition.Clear();
            }

            return Ok(resultstring);
        }
        /// <summary>
        /// 生成退库
        /// </summary>
        /// <param name="assetList"></param>
        /// <param name="order"></param>
        /// <param name="TransferType"></param>
        /// <returns></returns>
        private bool GenerateRefund(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            Thread.Sleep(10000);
            #region 字段
            //新调拨单自定义字段
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            var vsss = _setting.First(x => x.Name == "测试退库自定义表单");

            var cunfang1 = _extendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");
            var useDepart = _extendFields.First(x => x.ObjectType == 70 && x.Name == "使用部门");
            var shopCode = _extendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var shopName = _extendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
            var addressBig = _extendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
            var TuiKuField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "退库后实际存放地");
            var CenterName = _extendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");
            var CenterCode = _extendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");

            var assetTableField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");


            var assetVTestTableField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");



            //自定义资产退库单
            var customBigcun = _extendFields.First(x => x.ObjectType == 70 && x.Name == "存放地大类");
            var customCunFang = _extendFields.First(x => x.ObjectType == 70 && x.Name == "实际存放地");
            var customTuiKu = _extendFields.First(x => x.ObjectType == 70 && x.Name == "退库配送方式");
            var customAssetdetails = _extendFields.First(x => x.ObjectType == 70 && x.Name == "资产详情");
            var customAssetList = _extendFields.First(x => x.ObjectType == 70 && x.Name == "资产列表");
            var customCategory = _extendFields.First(x => x.ObjectType == 70 && x.Name == "调入存放地大类");
            var remarks = _extendFields.First(x => x.ObjectType == 70 && x.Name == "退库单备注");
            var assetShopcode = _extendFields.First(x => x.ObjectType == 70 && x.Name == "店铺代码");
            var assetShopname = _extendFields.First(x => x.ObjectType == 70 && x.Name == "店铺名称");
            var assetCenterCode = _extendFields.First(x => x.ObjectType == 70 && x.Name == "成本中心代码");
            var assetCenterName = _extendFields.First(x => x.ObjectType == 70 && x.Name == "成本中心名称");
            #endregion

            var btime = "";
            Order OrderJson = new Order();

            btime = order.Data["modifiedTime"].ToString();

            var addressdate = string.Empty;
            var districtCodedate = string.Empty;
            bool qwe = false;

            JsonArray CunFang = new JsonArray();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();


            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[CunFangDiField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestCunFangDiField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    string str = string.Empty;
                    if (TransferType == "公司内调拨")
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[CunFangDiField2.FieldId].ToString() + "，调拨状态:" + item[assetAllotField2.FieldId].ToString();
                    }
                    else
                    {
                        str = $"调拨方式:" + TransferType + "，存放地：" + item[VTestCunFangDiField.FieldId].ToString() + "，调拨状态:" + item[assetVTestAllotField.FieldId].ToString();
                    }
                }
            }

            var deserializedArray = CunFang.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["CunFang"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            var asd = "";
            foreach (var itemqwe in resultArray)
            {
                foreach (var item in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = item[CunFangDiField2.FieldId]!.ToString();

                        asd = CunFangDiField2.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = yideaClient.GetAsset(item[assetBarcodeField2.FieldId]?.ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            addressdate = item[CunFangDiField2.FieldId]!.ToString();
                            districtCodedate = item[QuBuField2.FieldId]["label"]!.ToString();
                            //if (sate == 1 && user != null)
                            //{
                            JsonObject query = new JsonObject()

                            {
                                ["id"] = item["id"]?.GetValue<int>(),
                                //资产编码
                                ["barcode"] = item["barcode"]!.ToString(),
                                //资产名称
                                ["name"] = item[assetQueryField2.FieldId]?["name"]?.ToString(),
                                //使用人
                                ["user"] = item[UserField2.FieldId]?["label"]?.ToString(),
                                //使用部门
                                ["useDepartmentName"] = item[useDepart.FieldId]?["label"]?.ToString() ?? string.Empty,
                                //资产存放地大类                                                                     
                                [addressBig.FieldId] = new JsonObject
                                {
                                    ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                                },
                                //实际存放地
                                [cunfang1.FieldId] = item[CunFangDiField2.FieldId]?.ToString(),
                                //店铺名称
                                [shopName.FieldId] = item[assetShopname.FieldId]?.ToString() ?? string.Empty,
                                //店铺代码
                                [shopCode.FieldId] = new JsonObject
                                {
                                    ["value"] = item[assetShopcode.FieldId]?["value"]?.ToString(),
                                    ["label"] = item[assetShopcode.FieldId]?["label"]?.ToString(),
                                }
                                //成本中心名称
                                //[CenterName.FieldId] = item[assetCenterName.FieldId]?.ToString(),
                                //成本中心代码
                                //[CenterCode.FieldId] = item[assetCenterCode.FieldId]?.ToString()
                            };
                            query.Add(CenterName.FieldId, item[assetCenterName.FieldId]?.ToString());
                            query.Add(CenterCode.FieldId, item[assetCenterCode.FieldId]?.ToString());
                            objTui[customAssetdetails.FieldId] = dataValue;
                            dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                            //退库配送方式 
                            objTui[customTuiKu.FieldId] = new JsonObject
                            {
                                ["value"] = "03",
                                ["label"] = "物流/快递",
                            };
                            //存放地大类
                            objTui[customBigcun.FieldId] = new JsonObject
                            {
                                ["value"] = item[customCategory.FieldId]?["value"]?.ToString(),
                                ["label"] = item[customCategory.FieldId]?["label"]?.ToString(),
                            };
                            //实际存放地
                            objTui[customCunFang.FieldId] = item[CunFangDiField2.FieldId]?.ToString();

                        }
                    }
                    else if (TransferType == "公司间调拨" && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = item[VTestCunFangDiField.FieldId]!.ToString();

                        asd = VTestCunFangDiField.FieldId;

                        var b = itemqwe["CunFang"]!.ToString();
                        if (a == b)
                        {
                            var assetfrist = yideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
                            var asdsads = assetfrist.ManagerEmployeeName;
                            var sadwerq = assetfrist.ManagerEmployeeName;
                            var sate = assetfrist.State;
                            var user = assetfrist.User;
                            if (sate == 1 && user != null)
                            {
                                JsonObject query = new JsonObject()

                                {
                                    ["id"] = item["id"]?.GetValue<int>(),
                                    //资产编码
                                    ["barcode"] = item["barcode"]!.ToString(),
                                    //资产名称
                                    ["name"] = item["name"]?.ToString(),
                                    //使用人
                                    ["user"] = item["employeeSelect_dk9ny18k"]?["label"]?.ToString(),
                                    //使用部门
                                    ["useDepartmentName"] = item["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty,
                                    //资产存放地大类                                                                     
                                    [addressBig.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                        ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                    },
                                    //实际存放地
                                    [cunfang1.FieldId] = item["input_rousootb"]?.ToString(),
                                    //店铺名称
                                    [shopName.FieldId] = item["input_hdjpkhne"]?.ToString() ?? string.Empty,
                                    //店铺代码
                                    [shopCode.FieldId] = new JsonObject
                                    {
                                        ["value"] = item["select_li74i42i"]?["value"]?.ToString(),
                                        ["label"] = item["select_li74i42i"]?["label"]?.ToString(),
                                    }
                                };
                                objTui[customAssetdetails.FieldId] = dataValue;
                                dataValue.Add(new JsonObject { [customAssetList.FieldId] = query });
                                //退库配送方式 
                                objTui[customTuiKu.FieldId] = new JsonObject
                                {
                                    ["value"] = "03",
                                    ["label"] = "物流/快递",
                                };
                                //存放地大类
                                objTui[customBigcun.FieldId] = new JsonObject
                                {
                                    ["value"] = item["select_kddqvnb8"]?["value"]?.ToString(),
                                    ["label"] = item["select_kddqvnb8"]?["label"]?.ToString(),
                                };
                                //实际存放地
                                objTui[customCunFang.FieldId] = item["input_rousootb"]?.ToString();
                            }
                        }
                    }
                }

                objTui[remarks.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                UserDefinedForm newwtui = new UserDefinedForm();
                newwtui.FormId = vsss.Id;
                newwtui.JsonData = JsonSerializer.Serialize(objTui);
                //退库单
                if (dataValue.Count == 0)
                {
                    qwe = false;

                    dataValue.Clear();
                    objTui.Clear();
                }
                else
                {
                    //创建自定义表单
                    qwe = yideaClient.AddNewUserDefinedForm(newwtui);
                    if (qwe)
                    {

                        dataValue.Clear();
                        objTui.Clear();

                    }
                    else
                    {
                        qwe = false;
                        dataValue.Clear();
                        objTui.Clear();
                    }
                }
            }
            return qwe;
        }
        /// <summary>
        /// 生成领用单
        /// </summary>
        /// <returns></returns>
        private bool GenerateReceive(JsonArray assetList, CustomizedFormData order, string TransferType)
        {
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;

            #region 字段
            //新调拨单自定义字段
            var LingYongformId = _setting.First(x => x.Name == "新资产领用单");
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            var lingCunField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "领用后实际存放地");
            var assetTableField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
            var assetBarcodeField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
            var assetAllotField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
            var assetSAPField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
            var assetQueryField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
            var CunFangDiField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
            var QuBuField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
            var UserField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");
            var ChengbenField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入成本中心码");

            var assetVTestTableField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
            var assetVTestBarcodeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
            var assetVTestAllotField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
            var VTestTransferTypeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
            var assetVTestQueryField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
            var VTestCunFangDiField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
            var VTestQuBuField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
            var VTestUserField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");
            var VTestChengBenField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试(公司间)调入成本中心码");


            var DrawAssetDate = _extendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情");
            var DrawAssetDatequery = _extendFields.First(x => x.ObjectType == 61 && x.Name == "资产详情query");
            var DrawEmployee = _extendFields.First(x => x.ObjectType == 61 && x.Name == "员工选择");
            var DrawDepartment = _extendFields.First(x => x.ObjectType == 61 && x.Name == "部门选择");
            var DrawCunFang = _extendFields.First(x => x.ObjectType == 61 && x.Name == "存放地大类");
            var DrawDianPu = _extendFields.First(x => x.ObjectType == 61 && x.Name == "使用店铺");
            var DrawShiJi = _extendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地");
            var DrawWuLiu = _extendFields.First(x => x.ObjectType == 61 && x.Name == "物流信息");
            var DrawBeiZhu = _extendFields.First(x => x.ObjectType == 61 && x.Name == "备注");
            var DrawShiJiQuery = _extendFields.First(x => x.ObjectType == 61 && x.Name == "实际存放地query");
            var DrawChenBenCode = _extendFields.First(x => x.ObjectType == 61 && x.Name == "成本中心代码");


            #endregion
            var btime = "";//修改时间
            JsonArray name = new JsonArray();
            btime = order.Data["modifiedTime"].ToString();
            JsonObject objTui = new JsonObject();
            JsonArray dataValue = new JsonArray();

            foreach (var item in assetList)
            {
                if (TransferType == "公司内调拨" && item[UserField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[UserField2.FieldId]!["label"]!.ToString() + item[CunFangDiField2.FieldId]!.ToString() }));
                }
                else if (TransferType == "公司间调拨" && item[VTestUserField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                {
                    name.Add(JsonSerializer.Serialize(new { name = item[VTestUserField.FieldId]!["label"]!.ToString() + item[VTestCunFangDiField.FieldId]!.ToString() }));
                }
                else
                {
                    Dictionary<string, object> keys = new Dictionary<string, object>();
                    if (TransferType == "公司内调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[UserField2.FieldId]", item[UserField2.FieldId]);

                        keys.Add("调拨状态", item[assetAllotField2.FieldId].ToString());
                    }
                    if (TransferType == "公司间调拨")
                    {
                        keys.Add("调拨方式", TransferType);
                        keys.Add("item[VTestUserField.FieldId]", item[VTestUserField.FieldId]);
                        keys.Add("调拨状态", item[assetVTestAllotField.FieldId].ToString());
                    }
                    string erStr = JsonSerializer.Serialize(keys);
                    _logger.LogError($"生成自定义领用单--error TransferType:{TransferType}" + erStr);
                }
            }
            var deserializedArray = name.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
            // 使用Distinct方法去重，基于name属性定义去重规则
            var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["name"].ToString()).ToList();
            // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
            var resultArray = uniqueArray.Select(token => token).ToArray();
            bool ab = false;

            foreach (var item in resultArray)
            {
                var cunfang = "";
                var uservalue = "";//调入使用人value
                var userlabel = "";//调入使用人label
                var usercode = "";//调入使用人code
                var usertype = "";//调入使用人type
                var districtCode = "";//调入区部code
                var c = "";//实际存放地
                int departmentValue = 0;//部门代码value
                var departmentCode = "";//部门代码code
                var departmentLabel = "";//部门代码label
                var departmentType = "";//部门代码type
                var selectcunfangvalue = "";//select实际存放地value
                var selectcunfanglabel = "";//select实际存放地label
                var selectCunDaLeivalue = "";//select存放地大类value
                var selectCunDaLeilabel = "";//select存放地大类label
                var shopName = string.Empty;//店铺名称
                var shopCode = string.Empty;//店铺代码
                var shopValue = string.Empty;//店铺id
                foreach (var itemasset in assetList)
                {
                    var a = "";
                    if (TransferType == "公司内调拨" && itemasset[UserField2.FieldId] != null && itemasset[assetAllotField2.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[UserField2.FieldId]["label"]!.ToString() + itemasset[CunFangDiField2.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {

                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());
                            assetdatajsonling.Add("specs", itemasset["query_1690536112161"]?["specs"]?.ToString());
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());
                            //assetdatajsonling.Add("districtName", itemasset["districtName"]!.ToString());
                            assetdatajsonling.Add("select_1692243766053", new JsonObject
                            {
                                ["value"] = itemasset["select_1696820814413"]["value"].ToString(),
                                ["label"] = itemasset["select_1696820814413"]["label"].ToString(),
                                ["color"] = new JsonObject
                                {
                                    ["backgroundColor"] = "#52a8ff",
                                    ["foreColor"] = "#ffffff"
                                }
                            });
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset[ChengbenField2.FieldId]!.ToString());
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset[CunFangDiField2.FieldId]!.ToString();

                            districtCode = itemasset[QuBuField2.FieldId]["value"]!.ToString();
                            uservalue = itemasset["employeeSelect_1695217523213"]?["value"]?.ToString();
                            userlabel = itemasset["employeeSelect_1695217523213"]?["label"]?.ToString();
                            usercode = itemasset["employeeSelect_1695217523213"]?["code"]?.ToString();
                            usertype = itemasset["employeeSelect_1695217523213"]?["type"]?.ToString();
                            departmentValue = Convert.ToInt32(itemasset["departmentSelect_1699238334958"]?["value"]?.ToString());
                            departmentCode = itemasset["departmentSelect_1699238334958"]?["code"]?.ToString() ?? string.Empty;
                            departmentLabel = itemasset["departmentSelect_1699238334958"]?["label"]?.ToString() ?? string.Empty;
                            departmentType = itemasset["departmentSelect_1699238334958"]["type"].ToString() ?? string.Empty;
                            selectcunfangvalue = itemasset["select_1732633124408"]["value"].ToString();
                            selectcunfanglabel = itemasset["select_1732633124408"]["label"].ToString();
                            selectCunDaLeivalue = itemasset["select_1696820814413"]["value"].ToString();
                            selectCunDaLeilabel = itemasset["select_1696820814413"]["label"].ToString();
                            shopName = itemasset["input_1696820941201"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_1696820861963"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_1696820861963"]?["value"]?.ToString() ?? string.Empty;



                        }
                    }
                    else if (TransferType == "公司间调拨" && itemasset[VTestUserField.FieldId] != null && itemasset[assetVTestAllotField.FieldId].ToString() == "调拨成功")
                    {
                        a = itemasset[VTestUserField.FieldId]["label"]!.ToString() + itemasset[VTestCunFangDiField.FieldId]!.ToString();

                        var b = item["name"]!.ToString();
                        if (a == b)
                        {
                            JsonObject assetdatajsonling = new JsonObject();
                            assetdatajsonling.Add("id", itemasset["id"]!.GetValue<int>());
                            assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());//资产编码
                            assetdatajsonling.Add("name", itemasset["name"]!.ToString());//资产名称
                            assetdatajsonling.Add("specs", itemasset["specs"]?.ToString());//规格型号
                            assetdatajsonling.Add("assetTypeName", itemasset["assetTypeName"]!.ToString());//资产类别
                            assetdatajsonling.Add(DrawChenBenCode.FieldId, itemasset["input_1691661512030"]?.ToString());//调入成本中心代码
                            assetdatajsonling.Add("useCompanyName", itemasset["useCompanyName"]?.ToString());//使用公司                                         
                            JsonObject queryAble = new JsonObject
                            {
                                [DrawAssetDatequery.FieldId] = assetdatajsonling,
                                ["subId"] = itemasset["subId"]?.ToString(),
                                ["subIndex"] = itemasset["subIndex"].GetValue<int>(),
                                ["version"] = 2
                                //["subIndex"]

                            };

                            dataValue.Add(queryAble);
                            objTui[DrawAssetDate.FieldId] = dataValue;
                            c = itemasset["input_rousootb"]!.ToString();//实际存放地

                            districtCode = itemasset["districtSelect_x60b3v7s"]["value"]!.ToString();//调入区部code
                            uservalue = itemasset["employeeSelect_dk9ny18k"]?["value"]?.ToString();//使用人value
                            userlabel = itemasset["employeeSelect_dk9ny18k"]?["label"]?.ToString();//使用人label
                            usercode = itemasset["employeeSelect_dk9ny18k"]?["code"]?.ToString();//使用人code
                            usertype = itemasset["employeeSelect_dk9ny18k"]?["type"]?.ToString();//使用人type
                            departmentValue = itemasset["departmentSelect_2t6gk02j"]?["value"]?.GetValue<int>() ?? 0;//调入部门value
                            departmentCode = itemasset["departmentSelect_2t6gk02j"]?["code"]?.ToString() ?? string.Empty;//调入部们code
                            departmentLabel = itemasset["departmentSelect_2t6gk02j"]?["label"]?.ToString() ?? string.Empty;//调入部门label
                            departmentType = itemasset["departmentSelect_2t6gk02j"]["type"].ToString() ?? string.Empty;//调入部门type
                                                                                                                       //selectcunfangvalue = itemasset[""]["value"].ToString();

                            selectCunDaLeivalue = itemasset["select_kddqvnb8"]["value"].ToString();
                            selectCunDaLeilabel = itemasset["select_kddqvnb8"]["label"].ToString();
                            selectcunfanglabel = itemasset["input_rousootb"].ToString();
                            shopName = itemasset["input_hdjpkhne"]?.ToString() ?? string.Empty;
                            shopCode = itemasset["select_li74i42i"]?["label"]?.ToString() ?? string.Empty;
                            shopValue = itemasset["select_li74i42i"]?["value"]?.ToString() ?? string.Empty;
                        }
                    }
                }

                var opoiubhnij = 11111;
                objTui[DrawShiJi.FieldId] = c;
                objTui[DrawBeiZhu.FieldId] = "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成";
                objTui[DrawWuLiu.FieldId] = new JsonObject
                {
                    ["value"] = "03",
                    ["label"] = "物流/快递",
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui[DrawEmployee.FieldId] = new JsonObject
                {
                    ["value"] = uservalue,
                    ["label"] = userlabel,
                    ["code"] = usercode,
                    ["type"] = usertype
                };
                objTui[DrawDepartment.FieldId] = new JsonObject
                {
                    ["value"] = departmentValue,
                    ["label"] = departmentLabel,
                    ["code"] = departmentCode,
                    ["type"] = departmentType
                };

                objTui[DrawCunFang.FieldId] = new JsonObject
                {
                    ["value"] = selectCunDaLeivalue,
                    ["label"] = selectCunDaLeilabel,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#577eff",
                        ["foreColor"] = "#ffffff"
                    }
                };

                //if (TransferType == "公司内调拨")
                //{
                //    objTui[DrawDianPu.FieldId] = new JsonObject
                //    {
                //        ["value"] = selectcunfangvalue,
                //        ["label"] = selectcunfanglabel,
                //        ["color"] = new JsonObject
                //        {
                //            ["backgroundColor"] = "#52a8ff",
                //            ["foreColor"] = "#ffffff"
                //        }
                //    };
                //}
                //else
                //{
                //    objTui[DrawDianPu.FieldId] = selectcunfanglabel;
                //}
                objTui["input_1747725516998"] = shopName;
                objTui["input_1747725500531"] = shopCode;
                objTui["select_1744616605684"] = new JsonObject
                {
                    ["value"] = shopValue,
                    ["label"] = shopCode + " " + shopName,
                    ["color"] = new JsonObject
                    {
                        ["backgroundColor"] = "#52a8ff",
                        ["foreColor"] = "#ffffff"
                    }
                };
                objTui["version"] = "";


                var jsss = JsonSerializer.Serialize(objTui).ToString();

                UserDefinedForm NewDefinedForm = new UserDefinedForm() { FormId = LingYongformId.Id, JsonData = JsonSerializer.Serialize(objTui) };

                if (name.Count == 0)
                {

                    objTui.Clear();
                    dataValue.Clear();
                }
                else
                {
                    ab = false; /*= yideaClient.AddNewUserDefinedForm(NewDefinedForm);*/

                    _logger.LogInformation("领用单生成成功");

                    objTui.Clear();
                    dataValue.Clear();
                    if (ab == false)
                    {

                        objTui.Clear();
                        dataValue.Clear();
                    }
                }
            }

            return ab;
        }

        /// <summary>
        /// 恢复调拨单中资产使用人的使用部门
        /// </summary>
        /// <param name="NTRBarcode"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("RevertDept")]
        public IActionResult RevertDept(string NTRBarcode)
        {
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            var useDepart = _extendFields.First(x => x.ObjectType == 60 && x.Name == "公司内调拨.调入使用部门");
            var usePersaon = _extendFields.First(x => x.ObjectType == 60 && x.Name == "公司内调拨.调入使用人");
            //1 获取调拨单

            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = NTRBarcode
            });
            CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

            var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
            var assetList = datajson["table_1690536110546"].AsArray();

            var newAssetList = new JsonArray();
            foreach (var item in assetList)
            {
                var ckinedItem = JsonNode.Parse(item.ToJsonString());
                var varcode = ckinedItem["barcode"].ToString();
                var itemString = JsonSerializer.Serialize(ckinedItem);
                _logger.LogDebug($"----------开始对资产：{varcode}，开始处理-----------");
                Console.WriteLine($"----------开始对资产：{varcode}，开始处理-----------");
                //检查有使用人并且没有使用部门
                if (ckinedItem?[usePersaon.FieldId] != null && !itemString.Contains(useDepart.FieldId))
                {
                    var personCode = yideaClient.GetEmployee(ckinedItem?[usePersaon.FieldId]?["code"]?.ToString(), null);
                    if (personCode == null || string.IsNullOrWhiteSpace(personCode.DepartmentCode))
                    {
                        throw new Exception($"资产：{varcode},无使用人，异常报错");
                    }
                    var GetDepart = yideaClient.GetDepartment(personCode.DepartmentCode);
                    if (GetDepart == null)
                    {
                        throw new Exception($"资产：{varcode},无使用部门，异常报错");
                    }
                    if (ckinedItem is JsonObject jsonobj)
                    {
                        var departmentObj = new JsonObject
                        {
                            ["value"] = GetDepart.Id,
                            ["code"] = GetDepart.Code,
                            ["label"] = GetDepart.Name,
                            ["type"] = "departmentName"
                        };
                        jsonobj.Add(useDepart.FieldId, departmentObj);
                    }
                }
                newAssetList.Add(ckinedItem);
            }
            datajson["table_1690536110546"] = newAssetList;
            var data = JsonSerializer.Serialize(datajson);
            UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = VformId.Id, JsonData = data };
            var updateResponse = yideaClient.UpdateUserDefinedForm(userDefinedForm, null);
            _logger.LogInformation("修改结果" + updateResponse);


            return Ok();
        }
        /// <summary>
        /// 领用单恢复使用部门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("RevertLY")]
        public IActionResult RevertLY()
        {
            List<string> SerialNoList = new List<string>();
            var VformId = _setting.First(x => x.Name == "新资产领用单");
            var LYperson = _extendFields.First(x => x.ObjectType == 61 && x.Name == "员工选择");
            var depart = _extendFields.First(x => x.ObjectType == 61 && x.Name == "部门选择");
            //1 获取调拨单



            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;

            string filePath = @"E:\YDYD\需要处理的单据.xlsx";
            // 【关键】设置许可证上下文，放在所有 EPPlus 操作之前
            // 【关键】设置许可证
            string resultstring = string.Empty;
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                // 获取第一个工作表（可根据实际Sheet名称修改，如 package.Workbook.Worksheets["Sheet1"]）
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                // 获取最大行号（已使用的行）
                int maxRow = worksheet.Dimension.End.Row;

                // 遍历 A 列（编号所在列，可根据实际列调整，如 worksheet.Cells[row, 2] 代表 B 列）
                for (int row = 1; row <= maxRow; row++)
                {
                    // 读取单元格值并转换为字符串
                    string cellValue = worksheet.Cells[row, 1].Value?.ToString();
                    if (!string.IsNullOrEmpty(cellValue))
                    {
                        SerialNoList.Add(cellValue);
                        _logger.LogInformation($"\n调拨单：{cellValue}，已加入队列");

                    }
                    else
                    {
                        _logger.LogInformation($"\n第{row}行为空");
                    }
                }
            }
            foreach (var item in SerialNoList)
            {
                var condition = new JsonArray();
                condition.Add(new JsonObject()
                {
                    ["field"] = "serialNo",
                    ["type"] = "input",
                    ["label"] = "流水号",
                    ["opt"] = "Equal",
                    ["val"] = item
                });
                Console.WriteLine($"--领用单：{item}---");
                CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
                var dataJson = JsonNode.Parse(order.Data["dataJson"].ToString());
                var personCode = yideaClient.GetEmployee(dataJson?[LYperson.FieldId]?["code"]?.ToString(), null);
                var GetDepart = yideaClient.GetDepartment(personCode.DepartmentCode);

                dataJson[depart.FieldId] = new JsonObject
                {
                    ["value"] = GetDepart.Code,
                    ["label"] = GetDepart.Name,
                    ["code"] = GetDepart.Code,
                    ["type"] = "departmentName"
                };
                string data = JsonSerializer.Serialize(dataJson);
                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = VformId.Id, JsonData = data };
                var updateResponse = yideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                _logger.LogInformation("修改结果" + updateResponse);
                if (userDefinedForm.ErrorMessage == null)
                {
                    Console.WriteLine($"领用单：{item}修改结束。。。。。。。");
                }

            }

            return Ok();


        }
        [HttpPost]
        [Route("Revertlydp")]
        public IActionResult Revertlydp(string NTRBarcode)
        {
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            //1 获取调拨单

            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = NTRBarcode
            });
            CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

            var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
            


            var assetList = datajson["table_1690536110546"].AsArray();

            JsonArray newassetlist = new JsonArray();
            for (int i = assetList.Count - 1; i >= 0; i--)
            {
                // 获取当前遍历的 JsonNode 元素
                JsonNode element = assetList[i];
                var barcode = element["input_1706236063428"].ToString();
                if (barcode.StartsWith("L"))
                {
                    continue;
                }
                else if (barcode == "Z1032207280051")
                {
                    continue;
                }
                else
                {
                    string jsonStr = element.ToJsonString();
                    JsonNode newElement = JsonNode.Parse(jsonStr)!;

                    newassetlist.Add(newElement);

                }
                    
                // 其他针对 element 的处理逻辑...
            }
            var last = 0;

            GenerateRefund(assetList, order, "公司内调拨");
            //GenerateReceive(assetList, order, "公司内调拨");
            return Ok();
        }


        [HttpPost]
        [Route("getdepart")]
        public IActionResult getdepart()
        {


            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;


            //部门选择
            //SubmitJson.Add(department.FieldId, new JsonObject
            //{

            //    ["value"] = 1176302,
            //    ["code"] = "1040512",
            //    ["label"] = "总部",
            //    ["type"] = "departmentName"
            //});

            var get = yideaClient.GetDepartment("1040512");
            return Ok();
        }
        #region 处理调拨单
        //[HttpPost]
        //[Route("ExpiryDisposal")]
        //public IActionResult ExpiryDisposal()
        //{
        //    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
        //    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
        //    RequestBase<SAPAssetClear> addAssetClearRequeste = new RequestBase<SAPAssetClear>();
        //    BaseInfo baseInfo = new BaseInfo();
        //    baseInfo.interID = "fico323";
        //    baseInfo.msgID = "005056A71F3E1EEE83E33DBE685AE065";
        //    baseInfo.transID = Guid.NewGuid();
        //    baseInfo.sender = "LAM";
        //    baseInfo.receiver = "SAP";
        //    baseInfo.sendTime = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));
        //    addAssetClearRequeste.baseInfo = baseInfo;
        //    List<SAPAssetClear> busiInfo = new List<SAPAssetClear>();
        //    int flag = 1;


        //    var condition = new JsonArray();
        //    condition.Add(new JsonObject()
        //    {
        //        ["field"] = "serialNo",
        //        ["type"] = "input",
        //        ["label"] = "流水号",
        //        ["opt"] = "Equal",
        //        ["val"] = "CLN202502120005"
        //    });


        //    var VformId = _setting.First(x => x.Name == "报废自定义表单");
        //    var clearquery = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();


        //    var datajson = clearquery.Data["dataJson"].ToString();
        //    JObject jObj = JObject.Parse(datajson);
        //    // 获取 table_1690336801324 对应的 JArray
        //    JArray jArray = jObj["table_1690336801324"] as JArray;

        //    foreach (var item in jArray)
        //    {
        //        SAPAssetClear assetClear = new SAPAssetClear();
        //        assetClear.ZDJBH = clearquery.Data["serialNo"].ToString();
        //        assetClear.ZDJLX = "ZCBF";
        //        assetClear.ZDJBH_IT = flag.ToString();//行项目
        //        assetClear.BUKRS = item["input_1691661510671"]?.ToString();//公司代码
        //        assetClear.ANLN1 = item["input_1691544111906"]?.ToString();//sap资产编码  财务编码
        //        assetClear.BUDAT = DateTime.Now.ToString("yyyyMMdd");//过账日期
        //        assetClear.SGTXT = assetClear.ANLN1 + "资产报废"; // 备注
        //        assetClear.ZBFLX = "BF01";//报废  类型编码 
        //        assetClear.ZBFLXTXT = "固定资产报废";//报废类型描述
        //        busiInfo.Add(assetClear);

        //        flag++;
        //    }

        //    addAssetClearRequeste.busiInfo = busiInfo;
        //    string jsonString = JsonSerializer.Serialize(addAssetClearRequeste);

        //    return Ok(new ApiResult(0, "", jsonString));
        //}
        ///// <summary>
        ///// 根据调拨单号生成退库和领用单据
        ///// </summary>
        ///// <param name="SerialNo"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("LifeTKandLY")]
        //public IActionResult LifeTKandLY()
        //{
        //    string resultstring = string.Empty;
        //    List<string> SerialNoList = new List<string>();
        //    string filePath = @"E:\YDYD\需要处理的单据.xlsx";
        //    // 【关键】设置许可证上下文，放在所有 EPPlus 操作之前
        //    // 【关键】设置许可证

        //    ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
        //    using (var package = new ExcelPackage(new FileInfo(filePath)))
        //    {
        //        // 获取第一个工作表（可根据实际Sheet名称修改，如 package.Workbook.Worksheets["Sheet1"]）
        //        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

        //        // 获取最大行号（已使用的行）
        //        int maxRow = worksheet.Dimension.End.Row;

        //        // 遍历 A 列（编号所在列，可根据实际列调整，如 worksheet.Cells[row, 2] 代表 B 列）
        //        for (int row = 1; row <= maxRow; row++)
        //        {
        //            // 读取单元格值并转换为字符串
        //            string cellValue = worksheet.Cells[row, 1].Value?.ToString();
        //            if (!string.IsNullOrEmpty(cellValue))
        //            {
        //                SerialNoList.Add(cellValue);
        //                _logger.LogInformation($"\n调拨单：{cellValue}，已加入队列");

        //            }
        //            else
        //            {
        //                _logger.LogInformation($"\n第{row}行为空");
        //            }
        //        }
        //    }
        //    SerialNoList = SerialNoList.Distinct().ToList();
        //    SerialNoList.Add("NTRA202507070034");
        //    var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
        //    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
        //    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
        //    foreach (var item in SerialNoList)
        //    {
        //        var condition = new JsonArray();
        //        condition.Add(new JsonObject()
        //        {
        //            ["field"] = "serialNo",
        //            ["type"] = "input",
        //            ["label"] = "流水号",
        //            ["opt"] = "Equal",
        //            ["val"] = item
        //        });
        //        CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();


        //        var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
        //        var assetList = datajson["table_1690536110546"].AsArray();

        //        var TuiKu = GenerateRefund(assetList, order, "公司内调拨");
        //        var LingYong = GenerateReceive(assetList, order, "公司内调拨");

        //        if (TuiKu)
        //        {
        //            resultstring += $"\n调拨单号：{item}，生成退库成功";
        //            _logger.LogInformation("调拨单号：{item}，生成退库成功");
        //        }
        //        else
        //        {
        //            resultstring += $"\n调拨单号：{item}，生成退库失败";
        //            _logger.LogInformation($"调拨单号：{item}，生成退库失败");
        //        }
        //        if (LingYong)
        //        {
        //            resultstring += $"调拨单号：{item}，生成领用成功";
        //            _logger.LogInformation($"调拨单号：{item}，生成领用成功");
        //        }
        //        else
        //        {
        //            resultstring += $"\n调拨单号：{item}，生成领用失败";
        //            _logger.LogInformation($"调拨单号：{item}，生成领用失败");
        //        }

        //        condition.Clear();
        //    }

        //    return Ok(resultstring);
        //}
        #endregion

        [HttpPost]
        [Route("RecionTry")]
        public IActionResult RecionTry(string serino)
        {

            string resultstring = string.Empty;
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = serino
            });
            _logger.LogInformation($"-------------开始对调拨单：{serino}  进行处理-----------");

            CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

            JsonArray assetList = new JsonArray();
            var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
            assetList = datajson["table_1690536110546"].AsArray();
            string DBType = datajson["radio_1732063332941"]!["label"]!.ToString();
            _logger.LogInformation($"----------------调拨方式：{DBType}  -----------");
            int errcount = 0;
            foreach (var item in assetList)
            {
                if (item["input_1729564737994"]!.ToString() != "调拨成功")
                {
                    errcount = errcount + 1;
                    break;
                }


            }
            if (errcount > 0)
            {
                #region 对调拨单部分失败进行处理
                var newAssetList = new JsonArray();
                foreach (var item in assetList)
                {
                    var clonedItem = JsonNode.Parse(item.ToJsonString());

                    var barcode = item["input_1706236063428"].ToString();
                    if (item["input_1729564737994"]!.ToString() != "调拨成功")
                    {
                        if (barcode.StartsWith("L"))
                        {
                            continue;
                        }
                        item["input_1729564737994"] = "调拨成功";
                        clonedItem["input_1729564737994"] = "调拨成功";
                        if (!item.AsObject().ContainsKey("input_1691544111906"))
                        {
                            var asset = yideaClient.GetAsset(barcode);
                            var DataJson = JsonSerializer.Deserialize<Dictionary<string, object>>(asset.DataJson);

                            // 添加新字段（如果不存在）
                            item.AsObject().Add("input_1691544111906", DataJson["input_1691544111906"].ToString());
                            clonedItem.AsObject().Add("input_1691544111906", DataJson["input_1691544111906"]?.ToString());

                        }
                    }
                    // 4. 将深拷贝并处理后的节点加入新数组
                    newAssetList.Add(clonedItem);

                }
                datajson["table_qes20gfc"] = newAssetList;
                var data = JsonSerializer.Serialize(datajson);
                //获取自定义表单
                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = Guid.Parse(order.Data["id"].ToString()), SerialNo = order.Data["serialNo"].ToString(), FormId = VformId.Id, JsonData = data };
                var updateResponse = yideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                _logger.LogInformation("修改结果" + updateResponse);
                if (!updateResponse)
                {
                    return NotFound(userDefinedForm.ErrorMessage);
                }
                #endregion
            }






            //过滤掉没有使用人的资产
            string targetKey = "employeeSelect_1695217523213";
            for (int i = assetList.Count - 1; i >= 0; i--)
            {
                var ssss = JsonSerializer.Deserialize<Dictionary<string, object>>(assetList[i]);
                var barcode = ssss["input_1706236063428"].ToString();
                var assetIndex = JsonSerializer.Serialize(assetList[i]);
                if (barcode.StartsWith("Z") && (!assetIndex.Contains("employeeSelect_1695217523213") || assetList[i]?["employeeSelect_1695217523213"] == null))
                {
                    assetList.RemoveAt(i);
                }
                if (barcode.StartsWith("L"))
                {
                    assetList.RemoveAt(i);
                }
            }


            //领用列表
            var assetList1 = new JsonArray();
            //退库和领用列表
            var assetList2 = new JsonArray();
            for (int i = 0; i <= assetList.Count - 1; i++)
            {
                var ly = assetList[i];
                var dbcode = ly["input_1706236063428"].ToString();
                var assetfrist = yideaClient.GetAsset(dbcode);

                //有调入使用人时，取当前资产使用人进行比较，如果资产无使用人，建领用单。
                if (string.IsNullOrEmpty(assetfrist.UserEmployeeName))
                {
                    string lyJson = ly.ToJsonString();
                    JsonNode newLy = JsonNode.Parse(lyJson)!;
                    //加入领用列表
                    assetList1.Add(newLy);
                }
                //资产有使用人，且不一致，建退库和领用
                if (!string.IsNullOrEmpty(assetfrist.UserEmployeeName) && ly["employeeSelect_1695217523213"]["label"].ToString() != assetfrist.UserEmployeeName)
                {
                    string lyJson = ly.ToJsonString();
                    JsonNode newLy = JsonNode.Parse(lyJson)!;
                    assetList2.Add(newLy);
                }


            }


            if (assetList1.Count > 0)
            {
                var LingYong = GenerateReceive(assetList1, order, DBType);
                if (LingYong)
                {
                    _logger.LogInformation($" assetList1_调拨单号：{serino}，生成领用成功");
                }
                else
                {
                    _logger.LogInformation($"assetList1_调拨单号：{serino}，生成领用失败");
                }

            }
            if (assetList2.Count > 0)
            {
                var TuiKu = GenerateRefund(assetList2, order, DBType);
                if (TuiKu)
                {
                    _logger.LogInformation($" assetList2_调拨单号：{serino}，生成退库成功");
                }
                else
                {
                    _logger.LogInformation($"assetList2_调拨单号：{serino}，生成退库失败");
                }
                var LingYong = GenerateReceive(assetList2, order, DBType);
                if (LingYong)
                {
                    _logger.LogInformation($" assetList2_调拨单号：{serino}，生成领用成功");
                }
                else
                {
                    _logger.LogInformation($"assetList2_调拨单号：{serino}，生成领用失败");
                }
            }
            _logger.LogInformation($"-------------调拨单：{serino}  处理结束-----------");




            return Ok();
        }
        [HttpPost]
        [Route("CBZXtRY")]
        public IActionResult CBZXtRY(string serino)
        {

            string resultstring = string.Empty;
            var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = serino
            });
            _logger.LogInformation($"-------------开始对调拨单：{serino}  进行处理-----------");

            CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

            JsonArray assetList = new JsonArray();
            var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
            assetList = datajson["table_1690536110546"].AsArray();
            string DBType = datajson["radio_1732063332941"]!["label"]!.ToString();
            _logger.LogInformation($"----------------调拨方式：{DBType}  -----------");

            //将调拨单内的资产和资产太台账对比  如果成本中心不一致  更新资产台账的成本中心，生成退库和领用
            //foreach (var item in assetList)
            //{
            //    var barcode = item["input_1706236063428"].ToString();
            //    var cbzxName = item["select_1732633124408"]["label"].ToString();
            //    var cbzxCode = item["input_1695218998531"].ToString();
            //    var asset = yideaClient.GetAsset(barcode);
            //    var assetTostr = asset.DataJson.ToString();
            //    var assetData = JsonSerializer.Deserialize<Dictionary<string, object>>(assetTostr);
            //    var asscbzxname = assetData["input_1694145393345"].ToString();
            //    var asscbzxcode = assetData["input_1691661512030"].ToString();


            //    if (asscbzxname != cbzxName && asscbzxcode != cbzxCode)
            //    {
            //        assetData["input_1694145393345"] = cbzxName;
            //        assetData["input_1691661512030"] = asscbzxcode;
            //        asset.DataJson = JsonSerializer.Serialize(assetData);

            //        var isnoll = yideaClient.UpdateAsset(asset, asset);

            //    }





            //}





            ////过滤掉没有使用人的资产
            //string targetKey = "employeeSelect_1695217523213";
            //for (int i = assetList.Count - 1; i >= 0; i--)
            //{
            //    var ssss = JsonSerializer.Deserialize<Dictionary<string, object>>(assetList[i]);
            //    var barcode = ssss["input_1706236063428"].ToString();
            //    var assetIndex = JsonSerializer.Serialize(assetList[i]);
            //    if (assetIndex.Contains("employeeSelect_1695217523213"))
            //    {
            //        if (assetList[i]?["employeeSelect_1695217523213"] != null)
            //        {
            //            assetList.RemoveAt(i);
            //        }

            //    }

            //}

            var ly = GenerateReceive(assetList, order, DBType);
            if (ly)
            {
                _logger.LogInformation($" assetList_调拨单号：{serino}，生成退库成功");
            }
            else
            {
                _logger.LogInformation($"assetList_调拨单号：{serino}，生成退库失败");
            }


            _logger.LogInformation($"-------------调拨单：{serino}  处理结束-----------");




            return Ok();
        }


        [HttpPost]
        [Route("vformnew")]
        public IActionResult vformnew(string serino)
        {

            var form = _setting.First(e => e.Name == "新资产批量调拨单");
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var condition = new JsonArray();
            condition.Add(new JsonObject()
            {
                ["field"] = "serialNo",
                ["type"] = "input",
                ["label"] = "流水号",
                ["opt"] = "Equal",
                ["val"] = serino
            });

            CustomizedFormData order = yideaClient.GetCustomizedFormDatas(form.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();
            return Ok();
        }
    }
}






